package com.jxb.demo.handler;

import com.alibaba.fastjson.JSONObject;
import com.jxb.demo.common.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @desc 处理统一返回值/统一全局异常
 */
@ControllerAdvice(basePackages = "com.jxb.demo.controller")
public class ResponseResultHandler implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }


    /**
     * @desc 修饰responsebody
     * @param o 对象体
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //返回默认信息
        if(o == null){
           return new ResponseResult<>();
        }
        if(o instanceof ResponseResult){
            return o;
        }
        return JSONObject.toJSONString(new ResponseResult<>().setData(o));
    }

    /**
     * @desc 统一异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception e){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode("1111");//异常
        responseResult.setMsg(e.getMessage());
        return responseResult;
    }

}
